import fm

class BraceMatchController:
	def __init__(me,doc):
		me.is_displaying_match = False
		me.doc                 = doc
		me.edit                = doc.Edit
		
		me.wire_events()
		
	def wire_events(me):
		fm.EventBus.ListenFor(me.doc, me.on_updateui, me.doc.EVTMSK_UPDATEUI)
		
	def on_updateui(me):
		me.undisplay_prev_match()
		me.display_match()
			
	def undisplay_prev_match(me):
		if not me.is_displaying_match: return
		
		#me.edit.BraceBadLight(-1)
		me.edit.BraceHighlight(-1,-1) # this appears to clear both highlights out, good or bad

		me.is_displaying_match=False

	def display_match(me):
		pos1=me.edit.GetCurrentPos()-1
		
		if pos1<0: return # 1st caret position in file
		
		c=chr(me.edit.GetCharAt(pos1))
		
		if c not in '()[]{}<>': return
		
		pos2=me.edit.BraceMatch(pos1)
		
		if pos2==-1:
			#print 'bad',pos1
			me.edit.BraceBadLight(pos1)
		else:
			#print 'good',pos1,pos2
			me.edit.BraceHighlight(pos1,pos2)
			
		me.is_displaying_match=True